<template>
    <div class="wrapper">
        <header class="topbar"></header>
        <div v-if="!isLogin" class="Basicinfo-notlogin" @click="goLogin">
            <img :src="defaultAvatar" />
            <div class="Name-and-Id">
                <h3>未登录用户</h3>
                <p>账户ID</p>
            </div>
        </div>

        <div v-else class="Basicinfo" @click="goToEditUserInfo">
            <img :src="userImg" />
            <div class="Name-and-Id">
                <h3>{{ userName }}</h3>
            </div>
        </div>

        <div class="Addresss-and-Hongbao">
            <div class="Address-part" @click="goAddress">
                <div class="icon-container">
                    <i class="fa fa-map-marker Address-symbol"></i>
                </div>
                <div class="address-content">
                    <p>点击添加地址</p>
                </div>
            </div>

            <div class="Hongbao-part" @click="goToFound">
                <div class="Hongbao-picture">
                    <img :src="hbImg" />
                </div>
                <div class="Hongbao-content">
                    <p>账户红包</p>
                </div>
            </div>
        </div>

        <div class="management-tool">
            <p>管理工具</p>
        </div>

        <div class="tools-container">
            <div class="tools-item" @click="openFavorites">
                <i class="fa fa-heart favorites-symbol"></i>
                <p>我的收藏</p>
            </div>
            <div class="tools-item" @click="goToOrderList">
                <i class="fa fa-file-text-o orders-symbol"></i>
                <p>我的订单</p>
            </div>
            <div class="tools-item" @click="gotoComment">
                <i class="fa fa-comments comments-symbol"></i>
                <p>我的评价</p>
            </div>
            <div class="tools-item" @click="goToEditInformation">
                <i class="fa fa-vcard-o update-symbol"></i>
                <p>更改信息</p>
            </div>
            <div class="tools-item" v-if="isUser" @click="goOpenShop">
                <i class="fa fa-plus-square open-shop-symbol"></i>
                <p>我要开店</p>
            </div>

            <div class="tools-item" v-if="isLogin" @click="logout">
                <i class="fa fa-sign-out logout-symbol"></i>
                <p>退出登录</p>
            </div>
        </div>
    </div>
    <Footer />

    <div v-if="showFavModal" class="modal-mask" @click.self="closeFavorites">
        <div class="modal-panel">
            <div class="modal-header">
                <span>我的收藏</span>
                <button class="modal-close" @click="closeFavorites">×</button>
            </div>
            <div class="modal-body">
                <div v-if="favLoading">加载中...</div>
                <div v-else-if="favErr" class="error">{{ favErr }}</div>
                <ul v-else-if="favList.length">
                    <li v-for="biz in favList" :key="biz.businessId" @click="goToBusiness(biz.businessId)">
                        <img v-if="biz.businessImg" :src="getBusinessImg(biz.businessImg)" @error="onImgError" />
                        <span class="biz-name">{{ biz.businessName || ('商家 #' + biz.businessId) }}</span>
                    </li>
                </ul>
                <div v-else>暂无收藏</div>
            </div>
        </div>
    </div>
</template>

<script setup>
import Footer from '../components/Footer.vue'
import axios from 'axios'
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const tokenRef = ref('')               
const isLogin = computed(() => !!tokenRef.value)  

const userId = ref('')
const user = ref({})
const authsRef = ref([])

const showFavModal = ref(false)
const favLoading = ref(false)
const favErr = ref('')
const favList = ref([])

// 资源
const defaultAvatar = require('../assets/portrait.png')
const hbImg = require('../assets/hb2.png')

const auths = computed(() => authsRef.value)
const isUser = computed(() => auths.value.includes('USER'))

// 派生展示
const userName = computed(() => user.value.userName || '用户')
const userImg = computed(() => user.value.image || defaultAvatar)

function parseAuthorities(raw) {
  if (!raw) return []
  try {
    // 1) 已是数组（极少数情况下组件传入）
    if (Array.isArray(raw)) {
      return raw.map(it => {
        if (typeof it === 'string') return it.toUpperCase().replace(/^ROLE_/, '')
        if (it && typeof it === 'object') {
          const v = it.name || it.authority || it.role || it.code || ''
          return String(v).toUpperCase().replace(/^ROLE_/, '')
        }
        return String(it || '').toUpperCase().replace(/^ROLE_/, '')
      }).filter(Boolean)
    }
    // 2) 字符串：可能是 JSON 或逗号分隔
    const val = String(raw)
    if (val.trim().startsWith('[')) {
      const arr = JSON.parse(val)
      return parseAuthorities(arr) // 递归利用上面的分支
    }
    return val.split(/[,\s]+/)
      .filter(Boolean)
      .map(s => String(s).toUpperCase().replace(/^ROLE_/, ''))
  } catch {
    return []
  }
}
function refreshUser() {
    userId.value = sessionStorage.getItem('userId') || ''
    const username = sessionStorage.getItem('userName') ||
        localStorage.getItem('userName') ||
        ''
    user.value = { id: userId.value, userName: username }
    tokenRef.value = sessionStorage.getItem('token') || ''
    const rawAuth = sessionStorage.getItem('authorities') || localStorage.getItem('authorities') || ''
    authsRef.value = parseAuthorities(rawAuth)
}

onMounted(() => {
    refreshUser()
    const onStorage = (e) => {
        if (!e) return
        if (['user', 'token', 'userId', 'username'].includes(e.key)) refreshUser()
    }
    window.addEventListener('storage', onStorage)

    const onUserChanged = () => refreshUser()
    window.addEventListener('user-changed', onUserChanged)

    onUnmounted(() => {
        window.removeEventListener('storage', onStorage)
        window.removeEventListener('user-changed', onUserChanged)
    })
})

// 仅点击未登录卡片时进入登录
function goLogin() {
    router.push('/login')
}

// 其它入口直接跳转
function goAddress() { router.push('/userAddress') }
function goToFound() { router.push('/hongbao') }
function goToOrderList() { router.push('/orderList') }
function goToEditUserInfo() { router.push('/businessuserInfoedit') }
function gotoComment() { router.push('/usercomments') }
function goToEditInformation() { router.push('/password') }
function goOpenShop() { router.push('/businessRegister') }
function logout() {
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('userId')
    sessionStorage.removeItem('userName')
    sessionStorage.removeItem('username')
    sessionStorage.removeItem('authorities')
    // 如有本地持久化也一并清理（可选）
    localStorage.removeItem('userId')
    localStorage.removeItem('userName')
    localStorage.removeItem('username')

    // 刷新本页状态并通知其他组件
    refreshUser()
    window.dispatchEvent(new Event('user-changed'))

    // 跳转到登录或首页
    router.replace('/login')
}

async function openFavorites() {
    showFavModal.value = true
    favErr.value = ''
    favLoading.value = true
    try {
        // 取当前用户收藏列表（返回包含 businessId）
        const { data } = await axios.get('/star')
        const stars = Array.isArray(data?.data) ? data.data : []
        const ids = [...new Set(stars.map(s => s.businessId).filter(Boolean))]
        if (!ids.length) { favList.value = []; return }
        const results = await Promise.all(
            ids.map(id =>
                axios.get(`/businesses/${id}`)
                    .then(r => r.data?.data)
                    .catch(() => ({ id }))
            )
        )
        favList.value = results.map(d => ({
            businessId: d.businessId || d.id,
            businessName: d.businessName || '',
            businessImg: d.businessImg || ''
        }))
    } catch (e) {
        favErr.value = '加载失败'
        console.error(e)
    } finally {
        favLoading.value = false
    }
}
function closeFavorites() {
    showFavModal.value = false
}

function goToBusiness(businessId) {
    showFavModal.value = false
    router.push({ path: '/businessInfo', query: { businessId } })
}

function getBusinessImg(img) {
    // 网络图片直接返回
    if (img && (img.startsWith('http://') || img.startsWith('https://'))) {
        return img;
    }
    // 本地图片用 require
    try {
        return require('../assets/' + img);
    } catch (e) {
        // 图片不存在时返回默认图片
        return require('../assets/default.png');
    }
}
</script>

<style scoped>
.wrapper {
    width: 100%;
    height: 100%;
    padding-top: 0;
    padding-bottom: calc(20vw + env(safe-area-inset-bottom));
    /* 顶部空间由蓝条提供 */
}

.topbar {
    width: 100%;
    height: 14vw;
    background-color: #0097FF;
    padding-top: env(safe-area-inset-top);
}

/* 如保留，去掉字体指定 */
.wrapper header h3 {
    font-size: 6vw;
    font-weight: 700;
    color: #FFFFFF;
    margin: 0;
    font-family: inherit;
    /* 不指定字体 */
    text-align: center;
}

.wrapper .Basicinfo {
    width: 100%;
    height: 12vw;
    background-color: #F5F5F5;
    display: flex;
    user-select: none;
    cursor: pointer;
}

.wrapper .Basicinfo:hover {
    background-color: #eaeaea;
}

.wrapper .Basicinfo img {
    width: 12vw;
    height: 12vw;
    margin-left: 2vw;
}

.wrapper .Basicinfo .Name-and-Id {
    display: flex;
    flex-direction: column;
}

.wrapper .Basicinfo .Name-and-Id h3 {
    font-size: 4vw;
    font-weight: 400;
    color: #000;
    margin-top: 1vw;
    margin-left: 2vw;
}

.wrapper .Basicinfo .Name-and-Id p {
    font-size: 2vw;
    font-weight: 200;
    color: #696969;
    margin-top: 1vw;
    margin-left: 2vw;
}

.wrapper .Basicinfo-notlogin {
    width: 100%;
    height: 12vw;
    background-color: #F5F5F5;
    display: flex;
    user-select: none;
    cursor: pointer;
}

.wrapper .Basicinfo-notlogin img {
    width: 12vw;
    height: 12vw;
    margin-left: 2vw;
}

.wrapper .Basicinfo-notlogin .Name-and-Id {
    display: flex;
    flex-direction: column;
}

.wrapper .Basicinfo-notlogin .Name-and-Id h3 {
    font-size: 4vw;
    font-weight: 400;
    color: #000;
    margin-top: 1vw;
    margin-left: 2vw;
}

.wrapper .Basicinfo-notlogin .Name-and-Id p {
    font-size: 2vw;
    font-weight: 200;
    color: #696969;
    margin-top: 1vw;
    margin-left: 2vw;
}

.Addresss-and-Hongbao {
    width: 100%;
    height: 10vw;
    background-color: #FFFFFF;
    display: flex;
    user-select: none;
}

.Addresss-and-Hongbao .Address-part {
    width: 48%;
    height: 9vw;
    background-color: #F5F5F5;
    margin-top: 1vw;
    margin-left: 2%;
    display: flex;
    cursor: pointer;
}

.Addresss-and-Hongbao .Address-part .Address-symbol {
    color: #0097ff;
    font-size: 7vw;
    margin-top: 1vw;
    margin-left: 2vw;
}

.Addresss-and-Hongbao .Address-part:hover {
    background-color: #eaeaea;
}

.Addresss-and-Hongbao .Address-part .address-content p {
    font-size: 4vw;
    font-weight: 380;
    color: #0097ff;
    margin-top: 1vw;
    margin-left: 2vw;
}

.Addresss-and-Hongbao .Hongbao-part {
    width: 48%;
    height: 9vw;
    background-color: #F5F5F5;
    margin-top: 1vw;
    border-left: solid 0.1px #FFFFFF;
    display: flex;
    cursor: pointer;
}

.Addresss-and-Hongbao .Hongbao-part:hover {
    background-color: #eaeaea;
}

.Addresss-and-Hongbao .Hongbao-picture img {
    width: 6vw;
    height: 7vw;
    margin-top: 1vw;
    margin-left: 2.5vw;
}

.Addresss-and-Hongbao .Hongbao-content p {
    font-size: 4vw;
    font-weight: 380;
    color: #0097ff;
    margin-top: 1vw;
    margin-left: 2vw;
}

.management-tool {
    width: 100%;
    height: 5vw;
    border-bottom: solid 0.2px #DCDCDC;
    user-select: none;
}

.management-tool p {
    font-size: 3vw;
    color: #696969;
    margin-left: 2vw;
    margin-top: 1.2vw;
}

.tools-container {
    width: 100%;

    background-color: #FFFFFF;
    user-select: none;
    padding-bottom: 20vw;
}

.tools-container .tools-item {
    width: 100%;
    height: 10vw;
    display: flex;
    border-bottom: solid 0.2px #DCDCDC;
    align-items: center;
}

.tools-container .tools-item p {
    font-size: 3vw;
    font-weight: 400;
    color: #000;
    margin-top: 2.5vw;
    margin-left: 2vw;
}

.tools-container .tools-item:last-child {
    margin-bottom: 2vw;
}
.orders-symbol {
    font-size: 5vw;
    margin-top: 2.5vw;
    margin-left: 2vw;
    color: #A9A9A9;
}

.comments-symbol {
    font-size: 4.1vw;
    margin-top: 2.5vw;
    margin-left: 2vw;
    color: #A9A9A9;
}

.service-symbol {
    font-size: 5vw;
    margin-top: 2.5vw;
    margin-left: 2vw;
    color: #A9A9A9;
}

.update-symbol {
    font-size: 3.8vw;
    margin-top: 2.8vw;
    margin-left: 1.5vw;
    color: #A9A9A9;
}

.open-shop-symbol {
    font-size: 4.2vw;
    margin-top: 2.5vw;
    margin-left: 2vw;
    color: #38CA73;
}

.logout-symbol {
    font-size: 4.2vw;
    margin-top: 2.5vw;
    margin-left: 2vw;
    color: #ff4d4f;
}

/****************** 收藏弹窗部分 ******************/
.modal-mask {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, .4);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
}

.modal-panel {
    width: 88vw;
    max-height: 70vh;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 12px;
    border-bottom: 1px solid #eee;
    font-size: 16px;
}

.modal-close {
    background: transparent;
    border: 0;
    font-size: 20px;
    cursor: pointer;
}

.modal-body {
    padding: 8px 12px;
    overflow: auto;
}

.modal-body ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.modal-body li {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
    border-bottom: 1px solid #f5f5f5;
    cursor: pointer;
}

.modal-body img {
    width: 12vw;
    height: 12vw;
    object-fit: cover;
    border-radius: 6px;
}

.biz-name {
    font-size: 14px;
    color: #333;
}

.favorites-symbol {
    font-size: 4.2vw;
    margin-top: 2.5vw;
    margin-left: 2vw;
    color: #ff7875; /* 需要灰色可改为 #A9A9A9 */
}
</style>